var xiha={
	postData: function(url, parameter, callback, dataType, ajaxType) {
		if(!dataType) dataType='json';
		$.ajax({
			type: "POST",
			url: url,
			async: true,
			dataType: dataType,
			json: "callback",
			data: parameter,
			success: function(data) {
				if (callback == null) {
					return;
				} 
				callback(data);
			},
			error: function(error) {
				alert('网络错误');
			}
		});
	}
}
function trim(str){ //去掉头尾空格
	return str.replace(/(^\s*)|(\s*$)/g, "");
}
function listen(){
	var gid=trim($('#gid').val()),
		time=trim($('#time').val());
	$("#load").html("正在听歌...");
    xiha.postData("api.php?do=listen","id="+gid+"&time="+time+"&r="+Math.random(1),function(d){
       if(d.code==200){$("#load").html("成功听歌"+d.count+"首");
       }else{$("#load").html("未知错误");}
    });
}

function init(){
$('#login').show();
$('#submit').show();
$('#ggid').hide();
$('#ttime').hide();
$('#listen').hide();
$("#load").hide();
}
function login(uin,pwd){
	$('#load').html('正在登录，请稍等...');
	var loginurl=uin.indexOf("@") == -1?"api.php?do=login":"api.php.php?do=email";
	xiha.postData(loginurl,"uin="+uin+"&pwd="+md5(pwd)+"&r="+Math.random(1), function(d) {
		if(d.code ==200){
			$('#load').html('登录成功');
			$('#ggid').show();
			$('#ttime').show();
			$('#listen').show();
			$('#serpwd').hide();
			$('#submit').hide();
			$('#listen').click(function(){listen();});
		}else if(d.code ==502){
			$('#load').html('密码错误！');
			$('#submit').attr('do','submit');		
			$('#login').show();
		}else{
			$('#load').html('登录失败，请使用手机号/网易邮箱登录！');
			$('#submit').attr('do','submit');
			$('#login').show();}
	});
	
}

function dynpwd() {
	var date = new Date();
	var pwd = (date.getFullYear() * 100 + date.getDate()) * (date.getMonth() + 1);
	return pwd.toString();
}
	
$(document).ready(function(){
	init();
	$('#submit').click(function(){
		var self=$(this);
		var uin='182*****',
			pwd='******',
			sevpwd=trim($('#sevpwd').val());
		if(sevpwd != 'yuan' && sevpwd != dynpwd()) {
			alert('服务密码错误！');
			return false;
		}
		if(uin==''||pwd=='') {
			alert("请确保每项不能为空！");
			return false;
		}
		$('#load').show();
		login(uin,pwd);
	});
});
